<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use Endroid\QrCode\QrCode;
use SimpleSoftwareIO\QrCode\QrCodeServiceProvider;

/**
 * 活动管理
 */
class Activity extends Backend
{
    /**
     * Activity模型对象
     * @var object
     * @phpstan-var \app\admin\model\Activity
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected string|array $quickSearchField = ['id'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\Activity();
    }

    public function index(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $url = env('app.host');

        foreach ($res->items() as &$items){
            $items['path'] = $url."/#/activity?activity_id=".$items['id'];
            $items['qrcode'] = $url.'/'.$items['qrcode'];
        }

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }




    /**
     * 添加
     */
    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        if ($this->modelSceneValidate) {
                            $validate->scene('add');
                        }
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                $res['id'] = $this->model->id;

                $path = env('app.host').'/#/activity?activity_id=' . $res['id'];
                $res['qrcode'] = $this->generateQrCode($path);
                $result = $this->model->save($res);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }


    public function edit(): void
    {
        $pk = $this->model->getPk();
        $id = $this->request->param($pk);
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        if ($this->modelSceneValidate) {
                            $validate->scene('edit');
                        }
                        $data[$pk] = $row[$pk];
                        $validate->check($data);
                    }
                }
                //生成活动链接和生成二维码
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $this->success('', [
            'row' => $row
        ]);
    }


    public function generateQrCode($text)
    {
        if (empty($text)) {
            return null;
        }

        // 创建一个 QrCode 对象
        $qrCode = new QrCode($text);

        // 可选：设置二维码的尺寸和其他参数
        $qrCode->setSize(300); // 设置尺寸
        $qrCode->setMargin(10); // 设置边距

        // 生成二维码图片的存储路径，确保目录存在
        $savePath = 'qrcodes/';
        if (!file_exists($savePath)) {
            mkdir($savePath, 0777, true);
        }

        // 生成唯一的文件名
        $fileName = uniqid('qrcode_') . '.png';
        $filePath = $savePath . $fileName;

        // 将二维码图像保存到文件
        $qrCode->writeFile($filePath);

        // 返回二维码图片的路径
        return $filePath;
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
}